package com.cyzy.listen;

import com.alibaba.fastjson.JSON;
import com.cyzy.dto.Message;
import com.cyzy.dto.MessageType; // 添加缺失的导入
import com.cyzy.mapper.MessageMapper;
import com.cyzy.service.MessageService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import com.cyzy.service.NotificationService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
// 注意修改为你的主题和消费者组名
@RocketMQMessageListener(topic = "producer_topic", consumerGroup = "consumer-group-2")
public class ChatConsumer implements RocketMQListener<String> {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private MessageService messageService;
    @Autowired
    private NotificationService notificationService;


    @Override
    public void onMessage(String messageJson) {
        System.out.println("接收到原始消息: " + messageJson); // 优先打印原始消息
        try {
            // 将JSON字符串转换为自定义Message对象
            Message message = JSON.parseObject(messageJson, Message.class);
            String rawMessage = messageJson;
            // 获取消息类型（支持大小写不敏感处理）
            MessageType messageType = MessageType.MESSAGE; // 默认值
            System.out.println(message.getMessageType()+"666");
            if (message.getMessageType() != null) {
                messageType = message.getMessageType();
            }
            // 根据消息类型执行不同的业务逻辑
            switch(messageType) {
                case MESSAGE:
                    handleNormalMessage(message, rawMessage);
                    break;
                case UPDATE_MESSAGE:
                    handleUpdateMessage(message, rawMessage);
                    break;
                default:
                    System.out.println("未知的消息类型: " + messageType);
                    handleNormalMessage(message, rawMessage);
            }
        } catch (Exception e) {
            System.err.println("处理消息失败: " + e.getMessage());
            // 异常处理逻辑，如记录日志、消息重试等
        }
    }

    //普通消息
    private void handleNormalMessage(Message message, String rawMessage) {
        System.out.printf("收到普通消息 - 发送者: %s, 接收者: %s, 内容: %s%n",
            message.getFromUser(),
            message.getToUser(),
            message.getContent());
        String redisKey = "messages_" + message.getToUserid();
        String redisUnreadKey = "messages_unread_" + message.getToUserid();
        redisTemplate.delete(redisKey);
        redisTemplate.delete(redisUnreadKey);
        System.out.println("已删除缓存: " + redisKey + " 和 " + redisUnreadKey);
        messageService.insertMessage(
            message.getFromUser(),
            message.getToUserid(),
            message.getToUser(),
            message.getContent()
        );

        // 推送给接收者（基于SSE）
        notificationService.pushToUser(message.getToUserid(), message);
    }

    //处理修改消息
    private void handleUpdateMessage(Message message, String rawMessage) {
        System.out.printf("收到修改消息 - 发送者: %s, 接收者: %s, 内容: %s%n",
            message.getFromUser(),
            message.getToUser(),
            message.getContent());
        if (message.getMessageid() != null) {
            messageService.updateRead(message.getMessageid());
            String redisKey = "messages_" + message.getToUserid();
            String redisUnreadKey = "messages_unread_" + message.getToUserid();
            redisTemplate.delete(redisKey);
            redisTemplate.delete(redisUnreadKey);
            System.out.println("已删除缓存: " + redisKey + " 和 " + redisUnreadKey);
            // 推送已读更新给接收者
            notificationService.pushToUser(message.getToUserid(), message);
        } else {
            // 处理没有消息ID的情况
            System.err.println("修改消息缺少消息ID, 原始消息: " + rawMessage);
        }
    }
}
